package com.sjp.controller.admin;

import com.sjp.pojo.BlogCategory;
import com.sjp.pojo.dto.UserDto;
import com.sjp.service.*;
import com.sjp.util.Result;
import com.sjp.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TagService tagService;
    @Autowired
    private BlogService blogService;
    @Autowired
    private CommentService commentService;

    @GetMapping("/login")
    public String login(){
        return "admin/login";
    }

    @RequestMapping("/checkLogin")
    @ResponseBody
    public Result checkLogin(UserDto userDto, HttpServletRequest request){
        UserDto user = userService.queryUserByNameAndPassword(userDto);
        if(user == null){
            return ResultGenerator.genFailResult("用户名或密码错误！");
        }else {
            request.getSession().setAttribute("user",user);
            return ResultGenerator.genSuccessResult();
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return "redirect:admin/login";
    }

    @GetMapping({"/index","/"})
    public String index(Model model){
        // 查找分类总数
        int categories = categoryService.countCategory();
        // 查找标签总数
        int tags = tagService.countTag();
        // 查找博客总数，blogStatus = 0 -> 包括已发布和未发布
        int blog = blogService.countBlog(0);
        // 查找评论总数
        int commentTotal = commentService.countTotal();
        model.addAttribute("countTag",tags);
        model.addAttribute("countCategory",categories);
        model.addAttribute("countBlog",blog);
        model.addAttribute("commentTotal",commentTotal);
        return "admin/index";
    }

}
